package com.qf.controller;

import com.alibaba.fastjson.JSONObject;
import com.qf.pojo.Shop;
import com.qf.service.ShopService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/*
@author fu
@date 2022/3/2220:01
*/
@WebServlet("/findAllShop")
public class ShopController extends HttpServlet {

    //声明ShopService
    private ShopService shopService;

    //提供无参构造方法
    public ShopController(){
        //读取Spring的核心文件
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("Spring_config.xml");

        //获取ShopService接口子实现类对象--->交给Spring
        //@Service:没有给定标识,所以按照接口类型创建子实现类对象
        shopService = applicationContext.getBean(ShopService.class);

        //打印业务层对象地址
        System.out.println(shopService);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理响应的中文乱码
        response.setContentType("text/html;charset=utf-8");
        //调用业务接口
        List<Shop> shopList = shopService.getAllShop();
        //shopList---转换成json格式
        String jsonStr = JSONObject.toJSONString(shopList);
        System.out.println(jsonStr);
        //响应给浏览器
        response.getWriter().write(jsonStr);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request,response);
    }
}
